from fastapi import APIRouter, Request, Form
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from models import *
from douyin import task_user

dy_app = APIRouter()
templates = Jinja2Templates(directory="templates")


@dy_app.get('/task')
async def get_task(request: Request):
    uid = request.cookies.get('uid')
    tasks = task_user.query_task(uid)
    return templates.TemplateResponse('index.html', {'request': request, 'tasks': tasks})


@dy_app.post('/add')
async def add(request: Request, address: str = Form(), keyword: str = Form(), reword: str = Form()):
    keywords = keyword.split(',')
    rewords = reword.split(',')
    urls = address.split(',')
    uid = request.cookies.get('uid')
    tasks = task_user.query_task(uid)
    for url in urls:
        # 不在任务列，创建任务
        room_id = url.split('/')[-1]
        if room_id not in tasks.keys():
            await task_user.add_task(uid,url, keywords, rewords)
    return templates.TemplateResponse('index.html', {'request': request, 'tasks': tasks})


@dy_app.get('/data_page/{page}')
async def data_page(request: Request, page: int = 1):
    uid = request.cookies.get('uid')
    live_data_list = await live_data.filter(uid = uid)
    # Create the paginated list
    if live_data_list:
        paginated_data = [live_data_list[i:i + 50] for i in range(0, len(live_data_list), 50)]
        now_data = paginated_data[page - 1]
        total_pages = len(paginated_data)
    else:
        now_data = [live_data_list[i:i + 50] for i in range(0, len(live_data_list), 50)]
        total_pages = 0
    return templates.TemplateResponse('datalist.html',
                                      {'request': request, 'page': page, 'live_data_list': now_data,
                                       'total_pages': total_pages})


@dy_app.get('/del/{room_id}')
async def delete(request:Request,room_id: str):
    uid = request.cookies.get('uid')
    await task_user.del_task(uid,room_id)
    return RedirectResponse('/douyin/task')
